import payService from '@/api/modules/pay/pay.ts'
import useUserStore from '@/store/modules/user.ts'
// usePayment.ts（或当前组件顶部定义）

export async function checkBalance(requiredAmount: number): Promise<boolean> {
  const userStore = useUserStore()
  await userStore.getUserInfo()
  const balance = userStore.userInfo?.balanceNumber ?? 0
  return balance >= requiredAmount
}

export async function payWithBalance(orderCode: string, amount: number): Promise<any> {
  try {
    const res = await payService.balancePay({
      orderCode,
      totalFeel: amount,
    })

    if (res?.code === 200) {
      return res
    }
    else {
      return res
    }
  }
  catch (err) {
    console.error('余额支付异常:', err)
    return err
  }
}

export async function payWithWeChat(orderCode: string, amount: number, body: string) {
  const { code: wxCode } = await uni.login({ provider: 'weixin' })

  const payParams = {
    code: wxCode,
    orderCode,
    totalFeel: amount,
    body,
  }

  const payRes = await payService.miniAppPay(payParams)
  const { data } = payRes
  const paymentData = {
    timeStamp: data.timeStamp,
    nonceStr: data.nonceStr,
    package: data.package,
    signType: data.signType,
    paySign: data.paySign,
  } as UniNamespace.RequestPaymentOptions

  return uni.requestPayment(paymentData)
}

